import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import config from '@/config'
import iView from 'iview'
import { setToken, getToken, canTurnTo, setTitle } from '@/lib/util'
import {route} from './routes'
const { homeName } = config
Vue.use(Router)
const LOGIN_PAGE_NAME = 'login'

const turnTo = (to, access,next) => {
  if (canTurnTo(to.name,access)) {
  	if(to.path==='/imglist'||to.path === '/previewfxyj'||to.path === '/previewsspd'||to.path==='/imgeditor'||to.path==='/preview'||to.path==='/previewtjt'||to.path==='/previewhome'||to.path==='/error_401'){
	     next();
  	}else{
  	   next('/login')
  	}
  } // 有权限，可访问
  else next('/error_401') // 无权限，重定向到401页面
}

const router = new Router({
  mode:'hash',
  routes: route
})

/*
 	登录token管理与过滤
 */
router.beforeEach((to, from, next) => {
  // iView.LoadingBar.start()
  const token = getToken('token');
  // 牧场未登陆则返回到牧场登录页;
  if (to.path === '/previewsspd'||to.path === '/previewhome'||to.path === '/previewfxyj'||to.path === '/previewtjt') {
    if (!to.query.token) {
      location.href="http://192.168.9.152:8082/#/main";
      return;
    }
    next();
  }
  if (to.path === '/preview'||to.path === '/previewsspd'||to.path === '/previewhome'||to.path === '/previewfxyj'||to.path === '/previewtjt') {
    next();
  }else if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    if (store.state.user.hasGetInfo) {
      turnTo(to, store.state.user.access, next);
    } else {
      store.dispatch('getUserInfo').then(user => {
        // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;
        turnTo(to, user.access, next)
      }).catch(() => {
        setToken('token',"")
        next({
          name: 'login'
        })
      })
    }
  }
})

// router.afterEach(to => {
//   setTitle(to, router.app)
//   // iView.LoadingBar.finish()
//   window.scrollTo(0, 0)
// })

export default router